package com.mall.user.services;

import com.mall.user.IUserService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.UserConverter;
import com.mall.user.dal.persistence.UserInfoMapper;
import com.mall.user.dal.persistence.UserMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dal.entitys.User;
import com.mall.user.dal.entitys.UserInfo;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Classname IUserServiceImpl
 * @Description
 * @Date 2021/11/15 19:35
 * @Author terrance_swn
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class IUserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    UserConverter userConverter;

    private Map<String, String> map;

//    {
//        //性别
//        map = new HashMap<>();
//        map.put("0","男");
//        map.put("1","女");
//    }

    @Override
    public IUserRegisterResponse register(IUserRegisterRequest request) {

        IUserRegisterResponse response = new IUserRegisterResponse();

        try {
            //参数校验
            request.requestCheck();

            //业务逻辑(插入用户表+用户信息表+生成一个随机六位的校验码插入用户校验表)
            //一共三张表的操作

            //先插入用户信息表userinfo,可以获得uid用户插入user和userVerify表
            //首先学号和邮箱判重
            List<UserInfo> userInfos = userInfoMapper.selectAll();
            for (UserInfo userInfo : userInfos) {
                if(userInfo.getEmail().equals(request.getEmail()) || userInfo.getStuNo().equals(request.getStudentNo())){
                    response.setCode(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode());
                    response.setMsg(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage());
                    return response;
                }
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setName(request.getStudentName());
            userInfo.setStuNo(request.getStudentNo());
            userInfo.setGender(request.getGender());
            userInfo.setEmail(request.getEmail());
            userInfo.setIsDeleted(0);
            userInfo.setIsChosen(0);
            int affectedRows1 = userInfoMapper.insertUseGeneratedKeys(userInfo);
            //如何获得insertUseGeneratedKeys的id(id被自动存入userinfo中了)
            Long uid = userInfo.getId();

            //step2 插入user表相关信息
            //首先判断重复(username不能重复)
            List<User> users = userMapper.selectAll();
            if(users != null){
                for (User user : users) {
                    if(user.getUsername().equals(request.getUsername())){
                        response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
                        response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
                        return response;
                    }
                }
            }
            User user = new User();
            user.setId(null);
            user.setUid(uid);
            user.setUsername(request.getUsername());
            user.setPassword(DigestUtils.md5DigestAsHex(request.getPassword().getBytes()));
            user.setIsDeleted(0);
            int affectedRows2 = userMapper.insertSelective(user);

            //插入userVerify表
            UserVerify userVerify = new UserVerify();
            userVerify.setId(null);
            userVerify.setUid(uid);
            //生成六位的每个人专属的校验码
            String uuid = UUID.randomUUID().toString();
            userVerify.setVerifyCode(uuid.substring(0,6));
            userVerify.setIsDeleted(0);
            int affectedRows3 = userVerifyMapper.insert(userVerify);

            if(affectedRows1 != 1 || affectedRows2 != 1 || affectedRows3 != 1){
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            //注册成功
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.info(e.getMessage());
            response.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    @Override
    public IUserLoginResponse login(IUserLoginRequest request) {

        IUserLoginResponse response = new IUserLoginResponse();

        try {
            //参数校验
            request.requestCheck();

            //业务逻辑
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(DigestUtils.md5DigestAsHex(request.getPassword().getBytes()));
            user.setIsDeleted(0);
            User user1 = userMapper.selectOne(user);

            //返回值处理
            //用户名or密码验证失败
            if (user1 == null) {
                response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
                return response;
            }

            //走到这里，说明登录信息验证成功,获取token
            String token = JwtTokenUtils.builder().msg(request.getUsername()).build().creatJwtToken();

            response.setToken(token);
            response.setUsername(request.getUsername());
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        }catch (Exception e){
            log.info(e.getMessage());
            response.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    @Override
    public IUserInfoResponse getUserInfo(IUserInfoRequest request) {

        IUserInfoResponse response = null;
        try {
            //参数校验
            request.requestCheck();

            //业务逻辑
            IUserInfoDto iUserInfoDto = userMapper.selectUserInfo(request.getUsername());
            if(iUserInfoDto == null){
                response.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.SYSTEM_ERROR.getMessage());
                return response;
            }
            response = userConverter.userInfoDto2UserInfoResponse(iUserInfoDto);

            //返回值处理
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.info(e.getMessage());
            response.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.SYSTEM_ERROR.getMessage());
        }
        return response;
    }
}
